<template>
  <view>
    <u-navbar title="发帖" fixed placeholder left-icon="close" @leftClick="goBack()">
      <template slot="right">
        <u-button size="mini" type="primary" @click="doPublist">发布</u-button>
      </template>
    </u-navbar>
    <view class="content">
      <u-gap height="5px" bgColor="#f8f9fa"></u-gap>
      <view>
        <editor id="editor" placeholder="请勿发布违规信息，具体规则请参考《发帖手册》" @ready="onEditorReady"></editor>
        <!-- <u-textarea v-model="content" autoHeight
        style="background-color: #f8f9fa;" placeholder="请勿发布违规信息，具体规则请参考《发帖手册》" maxlength="5000"></u-textarea> -->
        <view class="imgPreview">
          <view v-for="(img, index) in imgList" :key="index" class="img">
            <u-image :src="img" @click="previewImg(img, index)"></u-image>
            <view class="img_delete" @click="delImg(img, index)">
              <u-icon name="close" color="#ffffff" :size="12"></u-icon>
            </view>
          </view>
        </view>
      </view>
      <view class="tools">
        <u-icon name="photo" :size="28" @click="getImg('0')"></u-icon>
        <u-icon name="camera" :size="28" @click="getImg('1')"></u-icon>
        <view style="display: flex;align-items: center;justify-content: flex-end;flex: 1;">
          <u-checkbox-group @change="checkChange">
            <u-checkbox :checked="anonymous" label="匿名发布" activeColor="#00a679" labelSize="14px" name="1"></u-checkbox>
          </u-checkbox-group>
        </view>
      </view>
    </view>

    <c-modal :show="show" content="退出将放弃当前内容" showCancel cancelText="放弃" confirmText="继续编辑" @cancel="cancel"
    @confirm="show = false"></c-modal>
  </view>
</template>

<script>
import {
  addForum
} from '@/api/forum'
import { mapGetters } from 'vuex'
import {
  uploadFile
} from '@/api/file'
export default {
  data() {
    return {
      content: '',
      imgList: [],
      fileList: [],
      images: [],
      show: false,
      anonymous: false
    }
  },
  computed: {
    ...mapGetters(['id', 'nickname', 'name'])
  },
  methods: {
    onEditorReady() {
      uni.createSelectorQuery().select('#editor').context((res) => {
        this.editorCtx = res.context
      }).exec()
    },
    goBack() {
      if((this.content ?? '') != '') {
        this.show = true
        return
      }
      uni.navigateBack()
    },
    cancel() {
      this.show = false
      uni.navigateBack()
    },
    doPublist() {
      this.editorCtx.getContents({
        success: content => {
          addForum({
            userId: this.id,
            content: content.html,
            anonymous: this.anonymous,
            images: JSON.stringify(this.images)
          }).then(res => {
            this.$toast.show({
              msg: res.msg
            })
            if(res.code === 200) {
              this.timer = setTimeout(() => {
                uni.navigateBack()
              }, 300);
            }
          })
        }
      })
    },
    checkChange(detail) {
      this.anonymous = detail.length > 0
    },
    getImg(type) {
      let sourceType = ['album']
      if(type == '0') {
        sourceType = ['album']
      }else if(type == '1') {
        sourceType = ['camera']
      }
      uni.chooseImage({
        sizeType: ['original', 'compressed'],
        sourceType,
        count: 99,
        success: ({ tempFilePaths, tempFiles }) => {
          if(tempFilePaths.length > 9) {
            this.$toast.show({
              msg: '最多只能选择9张图片'
            })
            return
          }
          if(this.imgList.length + tempFilePaths.length > 9) {
            this.$toast.show({
              msg: '最多只能选择9张图片'
            })
            return
          }
          for(let i = 0; i < tempFilePaths.length; i++) {
            if(this.imgList.length < 9) {
              const data = {}
              data.type = 'forum'
              data.file = tempFiles[i]
              data.uid = this.id
              data.waterText = this.anonymous ? this.nickname : this.name
              uploadFile({ data }).then(res => {
                if(res.code === 200) {
                  this.imgList.push(tempFilePaths[i])
                  this.fileList.push(tempFiles[i])
                  this.images.push(res.data.downUrl)
                }
              })
            }
          }
        }
      })
    },
    previewImg(img, index) {
      uni.previewImage({
        urls: this.imgList,
        current: index,
        fail: (error) => {
          this.$toast.show({
            msg: '预览失败'
          })
        }
      })
    },
    delImg(img, index) {
      this.imgList.splice(index, 1)
      this.fileList.splice(index, 1)
      this.images.splice(index, 1)
    },
  },
  beforeDestroy() {
	  this.timer && clearTimeout(this.timer)
  }
} 
</script>

<style scoped lang="scss">
  .content {
    background-color: #f8f9fa;
  }

  .imgPreview {
    display: flex;
    flex-wrap: wrap;
    padding-top: 10px;
    box-sizing: border-box;

    &::v-deep .u-image {
      width: 25vw !important;
      height: 25vw !important;
      padding: 5px 5px;
      box-sizing: border-box;

      uni-image {
        width: 100% !important;
        border-radius: 8px !important;
      }
    }

    .img {
      position: relative;
    }

    .img_delete {
      position: absolute;
      top: 0;
      right: 0;
      transform: translate(0 , 0);
      background-color: rgba($color: #000000, $alpha: .7);
      border-radius: 50%;
      padding: 3px;
    }
  }

  .tools {
    position: absolute;
    bottom: 0;
    display: flex;
    align-items: center;
    width: 100%;
    height: 40px;
    background-color: #ffffff;
    padding: 0 20px;
    box-sizing: border-box;

    .u-icon {
      margin-right: 10px;
    }
  }

  .buttons {
    display: flex;
    align-items: center;
  }

  .ql-container {
    height: calc(100vh - var(--status-bar-height) - 44px - 40px - 320px);
    padding: 10px;
    box-sizing: border-box;
  }
</style>